﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using RealState.BLL;
using log4net;
using System.Data;
using RealState.Utils;
using Geekees.Common.Controls;

namespace RealState.W.AdminControl
{
    public partial class CategoriesEdit : System.Web.UI.UserControl
    {
        #region Private variants
        private CategoriesBLL m_CategoriesBL;
        private CategoryTypesBLL m_CategoriesTypeBL;
        private RealState.BusinessObjects.Categories m_CategoriesDO;
        protected ILog log = LogManager.GetLogger(typeof(CategoriesEdit));
        private static int selectedNode = 0;
        #endregion


        public void bindData()
        {
            if (!string.IsNullOrEmpty(Request.QueryString["ID"]))
            {
                m_CategoriesBL = new CategoriesBLL();
                m_CategoriesTypeBL = new CategoryTypesBLL();
                m_CategoriesDO = new RealState.BusinessObjects.Categories();
                try
                {
                    DataTable pages = Converter.ToDataTable(m_CategoriesBL.GetCategoriess());
                    ViewState["pages"] = pages;
                    populateTreeView(pages);

                    m_CategoriesDO =  m_CategoriesBL.GetCategories(Int32.Parse(Request.QueryString["ID"]));
                    txtTitle.Text = m_CategoriesDO.Title;
                    selectedNode =  m_CategoriesDO.ParentId;
                    //if (m_CategoriesDO.ParentId == 0)
                   //     MainMenu.S
                    //else
                    getSelectedNode(MainMenu.RootNode, selectedNode);
                    //drdGroups.DataSource = m_CategoriesTypeBL.GetCategoryTypess();
                    //drdGroups.DataTextField = "Title";
                    //drdGroups.DataValueField = "ID";
                    //drdGroups.DataBind();
                    //drdGroups.SelectedValue = m_CategoriesDO.CategoryType.ToString();
                    DropDownList1.SelectedValue = m_CategoriesDO.Position.ToString();
                    if (m_CategoriesDO.IsActive == true)
                        cbEnableClick.Checked = true;

                }
                catch (Exception ex)
                {
                    log.Error(ex.Message);
                }
                finally
                {
                    m_CategoriesBL = null;
                }
            }

        }

        protected void getSelectedNode(ASTreeViewNode parentNode, int parent)
        {

            foreach (ASTreeViewNode node in parentNode.ChildNodes)
            {
                if (Int32.Parse(node.NodeValue) == selectedNode)
                {
                    MainMenu.SelectNode(node.NodeValue);
                }
                getSelectedNode(node, parent);
            }
        }

        protected void getNodeByID(ASTreeViewNode parentNode, int parent, ref ASTreeViewNode returnValue)
        {
            try
            {

                foreach (ASTreeViewNode node in parentNode.ChildNodes)
                {
                    if (Int32.Parse(node.NodeValue) == parent)
                    {
                        returnValue = node;
                    }

                    getNodeByID(node, parent, ref returnValue);
                }
            }
            catch (Exception ex)
            {
                log.Error("getNodeByID: " + ex.Message);
            }
            finally
            {
            }
        }

        protected void populateTreeView(DataTable pages)
        {
            try
            {
                bool flag;
                pages.Columns.Add("inserted");
                MainMenu.RootNode.ChildNodes.Clear();
                MainMenu.RootNodeValue = "0";
                foreach (DataRow row in pages.Rows)
                {
                    string nodeText = row["TITLE"].ToString().Trim();
                    string nodeValue = row["ID"].ToString().Trim();

                    if (Int32.Parse(row["PARENTID"].ToString()) == 0)
                    {
                        ASTreeViewNode child = new ASTreeViewNode(nodeText, nodeValue, "~/AdminPanel/plugins/astree/astreeview/images/astreeview-folder-open.gif");
                        MainMenu.RootNode.AppendChild(child);
                    }
                }
                do
                {
                    flag = false;
                    foreach (DataRow row2 in pages.Rows)
                    {
                        string str4 = row2["TITLE"].ToString().Trim();
                        string str5 = row2["ID"].ToString().Trim();
                        int parent = Int32.Parse(row2["PARENTID"].ToString());

                        if ((parent > 0) && (row2["inserted"].ToString().Trim() == ""))
                        {
                            ASTreeViewNode node2 = new ASTreeViewNode(str4, str5, "~/AdminPanel/plugins/astree/astreeview/images/astreeview-folder-open.gif");
                            ASTreeViewNode returnValue = null;
                            getNodeByID(MainMenu.RootNode, parent, ref returnValue);
                            if (returnValue == null)
                            {
                                flag = true;
                            }
                            else
                            {
                                returnValue.AppendChild(node2);
                                row2["inserted"] = "1";
                            }
                        }
                    }
                }
                while (flag);
            }
            catch (Exception ex)
            {
                log.Error("populateTreeView" + ex.Message);
            }

        }


        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                bindData();
            }
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            if (!Page.IsValid)
                return;
            ASTreeViewNode selectedNode = MainMenu.GetSelectedNode();
            if (selectedNode == null)
            {
                JavaScript.Error("Bạn chưa chọn danh mục !", this.Page);
                return;
            }

            m_CategoriesDO = new RealState.BusinessObjects.Categories();
            m_CategoriesBL = new CategoriesBLL();
            try
            {
                m_CategoriesDO = m_CategoriesBL.GetCategories(Int32.Parse(Request.QueryString["ID"]));
                m_CategoriesDO.Id = Int32.Parse(Request.QueryString["ID"]);
                m_CategoriesDO.Title = txtTitle.Text;
                m_CategoriesDO.Position = Convert.ToInt32(DropDownList1.SelectedValue);
                if (selectedNode.NodeValue == "__root")
                    m_CategoriesDO.ParentId = 0;
                else
                    m_CategoriesDO.ParentId = Convert.ToInt32(selectedNode.NodeValue);
                if (cbEnableClick.Checked)
                    m_CategoriesDO.IsActive = true;
                else
                    m_CategoriesDO.IsActive = false;
                if (cbRemoveClick.Checked)
                    m_CategoriesDO.IsRemove = true;
                else
                    m_CategoriesDO.IsRemove = false;

                int result = m_CategoriesBL.UpdateCategories(m_CategoriesDO);
                if (result > 0)
                {
                    JavaScript.Success("Cập nhật thành công", Page, Request.Url.ToString());
                }
                else
                    JavaScript.Error("Có lỗi xảy ra ", Page);
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
            }
            finally
            {
                m_CategoriesBL = null;
                m_CategoriesDO = null;
            }
        }

    }
}